﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using Cost.Services;
using NBlock.Components.Excel;
using NBlock.Core;
using NBlock.MVCExtensions;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Cost.Controllers
{
    public class MaterialController : Controller
    {
        #region 构造函数
        private readonly ICostRepository<Material> materialRepository;
        private readonly ICostRepository<V_Material> vMaterialRepository;
        private readonly MaterialService materialService;
        private readonly IExcelImporter excelImporter;
        private readonly IEnumService enumService;

        public MaterialController(ICostRepository<Material> materialRepository,
            ICostRepository<V_Material> vMaterialRepository,
            IExcelImporter excelImporter,
            MaterialService materialService,
            IEnumService enumService)
        {
            this.materialRepository = materialRepository;
            this.vMaterialRepository = vMaterialRepository;
            this.excelImporter = excelImporter;
            this.materialService = materialService;
            this.enumService = enumService;
        }
        #endregion

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(string Id)
        {
            Material data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = materialRepository.Find(Id);
                data.CurrentPrice = materialService.GetMaterialPrice(data.Id, data.NeedProcess);
            }
            else
            {
                data = new Material
                {
                    NeedProcess = false,
                    Type = "RawMaterial",
                };
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(string Id)
        {
            var data = materialRepository.Find(Id) ?? new Material();
            TryUpdateModel(data);
            data.RawMaterialName = enumService.GetEnumText("Material", data.RawMaterialId);
            data.CurrentPrice = materialService.GetMaterialPrice(data.Id, data.NeedProcess);
            materialRepository.Save(data);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult Delete(string Id)
        {
            materialRepository.Delete(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteAll(string Ids)
        {
            var items = Ids.Split(',');
            materialRepository.DeleteAll(d => items.Contains(d.Id));
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult List(nbPageInfo pager, nbSearchCondition where)
        {
            var pagedata = materialRepository.GetPageable(pager, where);

            var list = new List<Material>(pagedata.Page.Count());
            foreach (var data in pagedata.Page)
            {
                data.CurrentPrice = materialService.GetMaterialPrice(data.Id, data.NeedProcess);
                list.Add(data);
            }
            return Json(pager.ToGridData(list, pagedata.Total));
        }

        #region 数据导入
        public ActionResult Import(string excelKey)
        {
            ViewBag.TemplateUrl = excelImporter.GetExcelTemplateUrl(excelKey);
            ViewBag.ExcelKey = excelKey;
            return View();
        }

        [HttpPost]
        public nbFileUploadJsonResult Import(HttpPostedFileBase file, string ExcelKey, string UpdateMode)
        {
            try
            {
                // 保留导入文档，以便后续检查
                var path = Server.MapPath("~/Upload/") + System.IO.Path.GetFileName(file.FileName).Replace(".", "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".");
                file.SaveAs(path);

            }
            catch (Exception ex)
            {
                // TODO 记录日志
            }
            var notMaterial = "";
            var data = excelImporter.Import(file, ExcelKey);
            foreach (var row in data.RepeatData.Rows)
            {
                var name = row["Name"];
                string id = string.Empty;
                try
                {
                    id = row["Id"];
                }
                catch
                {
                    id = string.Empty;
                }
                Material oldItem = null;
                if (!string.IsNullOrWhiteSpace(id))
                {
                    oldItem = materialRepository.Find(id);
                }
                else
                {
                    oldItem = materialRepository.Find(m => m.Name == name);
                }

                if (oldItem == null)
                {
                    oldItem = new Material { NeedProcess = false };
                }

                var item = row.ToEntity(oldItem);
                item.SafeStorage = item.SafeStorage ?? 0;
                if (!string.IsNullOrWhiteSpace(item.RawMaterialName))
                {
                    item.RawMaterialId = enumService.GetEnumValue("Material", item.RawMaterialName);

                    if (string.IsNullOrWhiteSpace(item.RawMaterialId))
                    {
                        // Todo 提示用户，找不到指定品名名称的品名
                        notMaterial += "," + item.RawMaterialName;
                    }
                }
                //if(item.ProcessRate.EndWith("%")
                // item.ProcessRate =double.Parse(dd.TrimEnd("%")) / 100;
                if (string.IsNullOrWhiteSpace(item.Code))
                {
                    item.Code = HZ2PY.GetFirstPY(item.Name);
                    var count = materialRepository.FindAll(i => i.Code == item.Code && i.Id != item.Id).Count();
                    if (count > 0)
                        item.Code = item.Code + count.ToString();
                }
                materialRepository.Save(item);
            }
            return new nbFileUploadJsonResult { Data = nbAjaxMessage.Successful };
        }

        #endregion

        #region LookUp
        public ActionResult LookUp(bool? NeedProcess, string Type)
        {
            ViewBag.NeedProcess = NeedProcess;
            ViewBag.Type = Type;
            return View();
        }

        [HttpPost]
        public JsonResult LookUp(bool? NeedProcess, string Type, nbPageInfo pager, nbSearchCondition where)
        {
            Expression<Func<V_Material, bool>> filter = null;
            if (NeedProcess.HasValue && !string.IsNullOrEmpty(Type))
                filter = m => m.NeedProcess == NeedProcess && m.BigClass == Type;
            else if (NeedProcess.HasValue)
                filter = m => m.NeedProcess == NeedProcess;

            var data = GetPageable(DateTime.Now, pager, where, filter);
            return Json(data);
        }

        /// <summary>
        /// 单选品名，参数p1为类型，参数p2为值，多个值用特殊符号隔开（如逗号）
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        /// <returns></returns>
        public ActionResult SingleLookUp(string p1, string p2)
        {
            ViewBag.p1 = p1;
            ViewBag.p2 = p2;
            return View();
        }

        [HttpPost]
        public JsonResult SingleLookUp(string p1, string p2, nbPageInfo pager, nbSearchCondition where)
        {
            Expression<Func<V_Material, bool>> filter = null;
            switch (p1)
            {
                case "RawMaterial": // 需要采购的品名
                    filter = m => m.NeedProcess == false;
                    break;
            }

            var data = GetPageable(DateTime.Now, pager, where, filter);
            return Json(data);
        }

        public ActionResult SingleLookUpRawMaterial()
        {
            return View();
        }

        [HttpPost]
        public JsonResult SingleLookUpRawMaterial(nbPageInfo pager, nbSearchCondition where)
        {
            Expression<Func<V_Material, bool>> filter = m => m.NeedProcess == false;
            var data = GetPageable(DateTime.Now, pager, where, filter);
            return Json(data);
        }

        #endregion

        /// <summary>
        /// 获取品名的分页数据
        /// </summary>
        /// <param name="date"></param>
        /// <param name="pager"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public nbJsonGridData GetPageable(DateTime date, nbPageInfo pager, nbSearchCondition where, Expression<Func<V_Material, bool>> filter = null)
        {
            if (filter == null)
            {
                filter = m => (date >= m.StartDate && date <= m.EndDate) || m.StartDate == null;
            }
            else
            {
                filter = filter.And(m => (date >= m.StartDate && date <= m.EndDate) || m.StartDate == null);
            }

            var pageData = vMaterialRepository.GetPageable(pager, filter, where);
            var v_Materials = pageData.Page.ToList();
            var materials = v_Materials.Select(m => new Material
            {
                Category = m.Category,
                Code = m.Code,
                CurrentPrice = m.Price,
                Id = m.Id,
                Name = m.Name,
                ProcessRate = m.ProcessRate,
                RawMaterialId = m.RawMaterialId,
                RawMaterialName = m.RawMaterialName,
                Remark = m.Remark,
                SafeStorage = m.SafeStorage,
                Specification = m.Specification,
                Type = m.Type,
                Unit = m.Unit,
                UpdateDate = m.UpdateDate,
                UpdateUser = m.UpdateUser,
                UpdateUserId = m.UpdateUserId,
                BigClass = m.BigClass,
            }).ToList();

            var data = pager.ToGridData(materials, pageData.Total);
            return data;
        }
    }
}
